import React, { useEffect, useState } from 'react'
import { Button, Table, Tag, Popconfirm, message, Switch } from 'antd'
import axios from 'axios'
import {
  DeleteOutlined,
  EditOutlined
} from '@ant-design/icons'


export default function RightList() {
  const [dataSource, setdataSource] = useState([])

  useEffect(() => {
    axios.get("/rights?_embed=children").then(res => {
      res.data[0].children = ""
      setdataSource(res.data)
    })
  }, [])

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      render: (id) => {
        return <b>{id}</b>
      }
    },
    {
      title: '权限名称',
      dataIndex: 'title',
    },
    {
      title: '权限路径',
      dataIndex: 'key',
      render: (key) => {
        return <Tag color="orange">{key}</Tag >
      }

    },
    {
      title: 'pagepermisson',
      dataIndex: 'pagepermisson',
    },
    {
      title: 'grade',
      dataIndex: 'grade',
    },
    {
      title: '操作',
      render: (item) => {
        return <div>
          <Popconfirm
            title="Delete the task"
            description="Are you sure to delete this task?"
            onConfirm={() => {
              confirm(item)
            }}
            onCancel={cancel}
            okText="Yes"
            cancelText="No"
          >
            <Button danger shape="circle" icon={<DeleteOutlined />}></Button>
          </Popconfirm>

          <Button type="primary" shape="circle" icon={<EditOutlined />} disabled={item.pagepermisson === undefined} />
          <Switch checked={item.pagepermisson === 1} onChange={
            () => {
              switchMethod(item)
            }
          }></Switch>
        </div>
      }

    },
  ];

  const delMethod = (item) => {
    if (item.grade === 1) {
      setdataSource(dataSource.filter(data => data.id !== item.id))
      axios.delete(`/rights/${item.id}`)
    } else {
      let list = dataSource.filter(data => data.id === item.rightId)
      list[0].children = list[0].children.filter(data => data.id !== item.id)
      setdataSource([...dataSource])
      axios.delete(`/children/${item.id}`)
    }
  };

  const switchMethod = (item) => {
    item.pagepermisson = item.pagepermisson === 1 ? 0 : 1
    setdataSource([...dataSource])
    if (item.grade === 1) {
      axios.patch(`/rights/${item.id}`, { pagepermisson: item.pagepermisson })
    } else {
      axios.patch(`/children/${item.id}`, { pagepermisson: item.pagepermisson })
    }
  };

  const confirm = (item) => {
    message.success('Click on Yes');
    delMethod(item)
  };
  const cancel = (e) => {
    // console.log(e);
    // message.error('Click on No');
  };

  return (
    <div>
      <Table dataSource={dataSource} columns={columns}
        pagination={{
          pageSize: 5
        }}
        rowKey={(item) => item.id}
      />
    </div>
  )
}
